<template>
  <div class="register-container">
    <el-card class="register-box">
      <div class="logo">
        <img :src="logoUrl" alt="Logo" class="logo-image">
      </div>
      <h2 class="register-title">用户注册</h2>

      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-position="top">
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
              clearable
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              prefix-icon="el-icon-message"
              clearable
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              show-password
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              prefix-icon="el-icon-lock"
              show-password
              class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="选择角色" prop="role">
          <el-select
              v-model="registerForm.role"
              placeholder="请选择角色"
              class="role-select"
          >
            <el-option label="农民" value="farmer"></el-option>
            <el-option label="消费者" value="consumer"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="handleRegister"
              class="register-btn"
              :loading="loading"
          >
            注册
          </el-button>
        </el-form-item>

        <div class="login-link">
          <span>已有账号？</span>
          <el-link type="primary" @click="goToLogin" class="login-link-text">返回登录</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import logoImage from '@/assets/logo.png';

export default {
  name: 'RegisterPage',
  data() {
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!value) {
        callback(new Error('请输入邮箱'));
      } else if (!emailRegex.test(value)) {
        callback(new Error('请输入有效的邮箱地址'));
      } else {
        callback();
      }
    };

    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.length < 6) {
        callback(new Error('密码长度不能少于6位'));
      } else {
        callback();
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };

    return {
      logoUrl: logoImage,
      loading: false,
      registerForm: {
        username: '',
        email: '',
        password: '',
        confirmPassword: '',
        role: 'farmer'
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, message: '用户名长度不能少于3位', trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    async handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (!valid) return;

        this.loading = true;
        try {
          const response = await axios.post('http://47.120.40.5:5000/api/user/register', {
            username: this.registerForm.username,
            password: this.registerForm.password,
            email: this.registerForm.email,
            role: this.registerForm.role
          });

          if (response.data.success) {
            this.$message.success('注册成功！');
            this.$router.push('/');
          }
        } catch (error) {
          if (error.response) {
            switch (error.response.status) {
              case 400:
                if (error.response.data.message.includes('用户名已存在')) {
                  this.$message.error('用户名已存在');
                } else if (error.response.data.message.includes('邮箱已被注册')) {
                  this.$message.error('邮箱已被注册');
                } else {
                  this.$message.error('请检查输入信息是否正确');
                }
                break;
              case 500:
                this.$message.error('服务器错误，请稍后重试');
                break;
              default:
                this.$message.error('注册失败，请稍后重试');
            }
          } else {
            this.$message.error('网络错误，请检查网络连接');
          }
        } finally {
          this.loading = false;
        }
      });
    },
    goToLogin() {
      this.$router.push('/');
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f0f2f5;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.register-box {
  width: 100%;
  max-width: 450px;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  border: none;
  background-color: rgba(255, 255, 255, 0.95);
}

.logo {
  text-align: center;
  margin-bottom: 20px;
}

.logo-image {
  height: 70px;
  width: auto;
  max-width: 100%;
  object-fit: contain;
  border-radius: 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-weight: 600;
  font-size: 22px;
  letter-spacing: 0.5px;
}

.custom-input {
  border-radius: 8px;
}

.custom-input >>> .el-input__inner {
  height: 44px;
  line-height: 44px;
}

.role-select {
  width: 100%;
}

.register-btn {
  width: 100%;
  margin-top: 10px;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #409eff;
  border-color: #409eff;
  transition: all 0.3s;
}

.register-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.login-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link-text {
  margin-left: 5px;
}

/* 手机端特定样式 */
@media (max-width: 480px) {
  .register-box {
    padding: 25px 15px;
    border-radius: 10px;
  }

  .logo-image {
    height: 60px;
    border-radius: 12px;
  }

  .register-title {
    font-size: 20px;
    margin-bottom: 25px;
  }

  .custom-input >>> .el-input__inner {
    height: 42px;
    line-height: 42px;
    font-size: 14px;
  }

  .register-btn {
    height: 42px;
    font-size: 15px;
  }

  .login-link {
    font-size: 13px;
  }
}
</style>